//
//  KZUserCenterVC.m
//  lg_zhinengbeikao_english
//
//  Created by 朱凯 on 2018/12/17.
//  Copyright © 2018年 zhukai. All rights reserved.
//

#import "KZUserCenterVC.h"
#import "BKNoteListVC.h"
// view
#import "KZUserCenterHeaderView.h"      // 头视图

@interface KZUserCenterVC () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) NSArray *items;
@property (nonatomic, strong) KZUserCenterHeaderView *headerView;
@end

@implementation KZUserCenterVC

#pragma mark - view cycle
- (void)viewDidLoad {
    [super viewDidLoad];

    _items = @[@[@"我的笔记", @"我的收藏", @"消息通知"],
               @[@"清理缓存", @"关于"],
               @[@"退出系统"],];
    
    [self createTableView];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self setNaviAttributeWithTranslucent:true stateBarLightContent:true];
}

#pragma mark - UITableViewDelegate
- (void)createTableView {
    
    self.table = [[UITableView alloc] init];
    self.table.backgroundColor = kBgColor;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0)).priorityMedium();
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);;
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        }
    }];
    
    _headerView = [[KZUserCenterHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, H(150))];
    _table.tableHeaderView = _headerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _items.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ((NSArray *)_items[section]).count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 || indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_normalItems"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell_normalItems"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.font = FONT(15);
            cell.textLabel.textColor = kBlackColor;
            cell.detailTextLabel.font = FONT(15);
            cell.detailTextLabel.textColor = UIColor.lightGrayColor;
        }
        cell.textLabel.text = [NSString stringWithFormat:@"%@", _items[indexPath.section][indexPath.row]];
        
        if (indexPath.row < ((NSArray *)_items[indexPath.section]).count - 1 &&
            [cell.contentView viewWithTag:9527] == nil) {
            UIView *line = [UIView new];
            line.tag = 9527;
            line.backgroundColor = kLineColor;
            [cell.contentView addSubview:line];
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(cell);
                make.height.equalTo(@0.5);
            }];
        }
        
        // 缓存
        if (indexPath.section == 1 && indexPath.row == 1) {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2lfM", [self cacheSize]/1000.0/1000.0];
        }
        
        return cell;
        
    }
    // 退出系统
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_logout"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell_logout"];
            UILabel *label = [[UILabel alloc] init];
            label.text = @"退出系统";
            label.font = FONT(15);
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = kBlackColor;
            [cell.contentView addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(label.superview);
            }];
        }
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return UIView.new;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return UIView.new;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:false];
    
    if(indexPath.section==0) {
        
        if (indexPath.row==0) {
            
            BKNoteListVC *vc = [[BKNoteListVC alloc] init];
            [self present:vc];
            
        }
        
    } else if (indexPath.section == 1) {
        // 清理缓存
        if (indexPath.row == 1) {
            [self clearCache];
        }
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 设置header背景的拉伸
    _headerView.offset = scrollView.contentOffset.y;
}



#pragma mark - 缓存
- (unsigned long long)cacheSize {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSLog(@"cachePath: %@", cachePath);
    NSDirectoryEnumerator<NSString *> *enumer = [fileManager enumeratorAtPath:cachePath];
    // 单位是B
    unsigned long long size = 0;
    for (NSString *subPath in enumer) {
        NSString *filePath = [cachePath stringByAppendingPathComponent:subPath];
        /*
         attributesOfItemAtPath：获得NSDictionary<NSFileAttributeKey, id>
         NSFileAttributeKey可以获得一些文件的属性，如大小
         */
        size += [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return size;
}
- (void)clearCache {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;

    NSDirectoryEnumerator<NSString *> *enumer = [fileManager enumeratorAtPath:cachePath];
    unsigned long long size = 0;
    for (NSString *subPath in enumer) {
        
        NSString *filePath = [cachePath stringByAppendingPathComponent:subPath];
        /*
         attributesOfItemAtPath：获得NSDictionary<NSFileAttributeKey, id>
         NSFileAttributeKey可以获得一些文件的属性，如大小
         */
        size += [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
        NSError *error;
        BOOL isSuccess = [fileManager removeItemAtPath:filePath error:&error];
        if (isSuccess && !error) {
            NSLog(@"删除成功");
        }
    }
    [self.table reloadData];
    
}
@end
